package com.zimmur.service.impl.account;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.zimmur.common.AppModuleEnum;
import com.zimmur.common.IDWorkFactory;
import com.zimmur.common.PropertiesCommon;
import com.zimmur.dao.account.IUserMessageDao;
import com.zimmur.model.account.UserMessage;
import com.zimmur.model.account.UserMessageParameter;
import com.zimmur.model.account.UserNewMessage;
import com.zimmur.model.account.view.UserMessageView;
import com.zimmur.model.order.OrderDetail;
import com.zimmur.service.account.IUserMessageService;
import com.zimmur.service.account.IUserNewMessageService;
import com.zimmur.service.order.IOrderDetailService;
import com.zimmur.tools.DateUtils;
import com.zimmur.tools.IdWorker;
import com.zimmur.tools.PageUtil;

@Service("userMessageService")
public class UserMessageServiceImpl implements IUserMessageService {
	private static Logger log = LoggerFactory.getLogger(UserMessageServiceImpl.class);
	
	@Resource
	private IUserNewMessageService userNewMessageService;
	@Resource
	private IOrderDetailService orderDetailService;
	
	@Resource
	private IUserMessageDao userMessageDao;

	private final static String SYSTEMICON="system.icon";
	
	@Override
	public boolean userMessageRead(Long userId, Long messageId) {
		if(userId>0 && messageId >0){
			UserMessage message = new UserMessage();
			message.setMessageId(messageId);
			message.setIsRead(1);
			message.setReadDate(DateUtils.getNowUnixTime());
			return userMessageDao.updateByPrimaryKeySelective(message)>0?true:false;
		}
		return false;
	}
	/**
	 * 获取系统未读消息
	 * @param userId
	 * @return
	 */
	public int getNoneSystemNum(long userId){
		UserMessageParameter parameter = new UserMessageParameter();
		parameter.setUserId(userId);
		parameter.setModuleId(Integer.parseInt(AppModuleEnum.Global.getModuleId()));
		parameter.setIsRead(0);
		return userMessageDao.selectPageListByUserIdCount(parameter);
	}
	
	@Override
	public UserMessageParameter selectByPage(long userId, int curPage, int pageSize,Integer isRead,AppModuleEnum moduleEnum) {
		UserMessageParameter parameter = new UserMessageParameter();
		parameter.setUserId(userId);
		parameter.setPageSize(pageSize);
		parameter.setModuleId(Integer.parseInt(AppModuleEnum.Global.getModuleId()));
		if(moduleEnum != AppModuleEnum.Global){
			int rowsCount = userMessageDao.selectPageListByUserIdExcludeModuleCount(parameter);
			parameter.setRowsCount(rowsCount);
			if(rowsCount>0 && curPage<= parameter.getTotalPage()){
				parameter.setCurrentPage(curPage);
				List<UserMessageView> pageData = userMessageDao.selectPageListByUserIdExcludeModule(parameter);
				if(pageData != null){
					for (UserMessageView userMessageView : pageData) {
						userMessageView.setMsgDate(DateUtils.getUnixTimeToDefineFormat(userMessageView.getCreateDate()));
					}
					parameter.setPageList(pageData);
				}
			}
		}else{
			if(isRead != null){
				parameter.setIsRead(isRead);
			}
			int rowsCount = userMessageDao.selectPageListByUserIdCount(parameter);
			parameter.setRowsCount(rowsCount);
			if(rowsCount>0 && curPage<= parameter.getTotalPage()){
				parameter.setCurrentPage(curPage);
				List<UserMessageView> pageData = userMessageDao.selectPageListByUserIdIncludeModule(parameter);
				if(pageData != null){
					for(UserMessageView userMessageView : pageData){
						userMessageView.setMsgDate(DateUtils.getUnixTimeToDefineFormat(userMessageView.getCreateDate()));
					}
					parameter.setPageList(pageData);
				}
			}
		}
		
		return parameter;
	}

	
	@Override
	public UserMessage selectById(Long userId, Long messageId) {
		return userMessageDao.selectByPrimaryKey(messageId);
	}

	@Override
	public List<UserMessage> selectNonePushList() {
		return userMessageDao.selectListByIsPush(0);
	}

	@Override
	public boolean updateMessagePushStatusByIds(List<UserMessage> list) {
		return userMessageDao.updateMessagePushStatusByIds(list)>0?true:false;
	}

	@Override
	public boolean updateReadStatus(UserMessage userMessage) {
		return userMessageDao.updateMessageReadStatus(userMessage)>0?true:false;
	}

	@Override
	public int countUserNoneReadNum(long userId) {
		return userMessageDao.selectCountByUserIdNoneRead(userId);
	}

	@Override
	public boolean addNewMessage(UserMessage message) {
		boolean flag=userMessageDao.insertSelective(message)>0?true:false;
		if(flag){
			try {
				int time=DateUtils.getNowUnixTime();
				UserNewMessage userNewMessage=new UserNewMessage();
				userNewMessage.setUserId(message.getToUserId());
				userNewMessage.setContent(message.getMsgContent());
				userNewMessage.setCategoryCode(message.getCategoryCode());
				userNewMessage.setUpdateDate(time);
				
				userNewMessageService.updateOrInsert(userNewMessage);
			} catch (Exception e) {
				log.error("addNewMessage:{}",e.getMessage());
			}
		}
		return flag;
	}
	@Override
	public boolean sendMessage(long fromUser,long toUserId,String title,String content,String dataId,String categoryCode,int moduleId ){
		UserMessage message = new UserMessage();
		message.setMessageId(IDWorkFactory.getID(AppModuleEnum.UserMessage));
		message.setUserId(fromUser);
		message.setMsgType("text");
		message.setToUserId(toUserId);
		message.setCategoryCode(categoryCode);
		message.setMsgTitle(title);
		message.setMsgContent(content);
		message.setDataId(dataId);
		message.setIsRead(0);
		message.setCreateDate(DateUtils.getNowUnixTime());
		message.setIsPush(0);
		message.setModuleId(moduleId);
		return addNewMessage(message);
	}
	@Override
	public PageUtil<UserMessageView> selectMessageByUserIdAndCategoryCode(long userId, String categoryCode,	Integer pageNow) {
		PageUtil<UserMessageView> pageUtil=new PageUtil<>();
		if(pageNow==0){
			pageNow=1;
		}
		pageUtil.setPageNo(pageNow);
		int totalNum=userMessageDao.countMessageByUserIdAndCode(userId, categoryCode);
		if(totalNum>0){
			pageUtil.setTotalRecord(totalNum);
			List<UserMessageView> userMessageViews=userMessageDao.selectMessageByUserIdAndCode(userId, categoryCode, pageUtil.getPageBeginNo(), pageUtil.getPageSize());
			
			List<Long> messageIDs=new ArrayList<>();
			
			String systemIcon=PropertiesCommon.getProperty(SYSTEMICON);
			if(userMessageViews != null && userMessageViews.size()>0){
				try {
					
					if("organization".equals(categoryCode)){
						
						for(UserMessageView userMessageView:userMessageViews){
							String orderId=userMessageView.getDataId();
							if(orderId!=null && !orderId.isEmpty()){
								List<OrderDetail> orderDetails=orderDetailService.selectByOrderId(Long.valueOf(orderId));
								if(orderDetails!=null && orderDetails.size()>0){
									userMessageView.setGoodsName(orderDetails.get(0).getGoodsTitle());
									userMessageView.setCoverImage(orderDetails.get(0).getCoverImage());
								}
							}
							if(userMessageView.getIsRead()==null ||userMessageView.getIsRead()==0 ){
								messageIDs.add(userMessageView.getMessageId());
							}
							String userIcon=userMessageView.getUserIcon();
							if(userIcon == null || userIcon.isEmpty()){
								userMessageView.setUserIcon(systemIcon);
							}
							userMessageView.setMsgDate(DateUtils.getUnixTimeToDefineFormat(userMessageView.getCreateDate()));
						}
					}else{
						for(UserMessageView userMessageView:userMessageViews){
							userMessageView.setMsgDate(DateUtils.getUnixTimeToDefineFormat(userMessageView.getCreateDate()));
							if(userMessageView.getIsRead()==null ||userMessageView.getIsRead()==0 ){
								messageIDs.add(userMessageView.getMessageId());
							}
							String userIcon=userMessageView.getUserIcon();
							if(userIcon == null || userIcon.isEmpty()){
								userMessageView.setUserIcon(systemIcon);
							}
						}
						
					}
					if(messageIDs.size()>0){
						try {
							int unixTime=DateUtils.getNowUnixTime();
							int flag=userMessageDao.updateMessagesIsRead(messageIDs, unixTime);
							log.info("update num:"+flag);
						} catch (Exception e) {
							log.error(e.getMessage(),e);
							// TODO: handle exception
						}
					}
				} catch (Exception e) {
					log.error(e.getMessage(),e);
				}
				pageUtil.setItemList(userMessageViews);
				try {
					if(userMessageViews!=null && !userMessageViews.isEmpty()){
						userNewMessageService.updateNumber(userId, categoryCode);
					}
				} catch (Exception e) {
					log.error("update UserNewMessage error");
					log.error(e.getMessage());
				}
			}
		}
		return pageUtil;
	}
	@Override
	public int addMessageList(List<UserMessage> userMessages) {
		int flag=userMessageDao.addMessageList(userMessages);
		if(flag>0){
			int time=DateUtils.getNowUnixTime();
			try {
				for(UserMessage userMessage:userMessages){
					UserNewMessage userNewMessage=new UserNewMessage();
					userNewMessage.setUserId(userMessage.getToUserId());
					userNewMessage.setContent(userMessage.getMsgContent());
					userNewMessage.setCategoryCode(userMessage.getCategoryCode());
					userNewMessage.setUpdateDate(time);
					userNewMessageService.updateOrInsert(userNewMessage);
				}
			} catch (Exception e) {
				log.error("addMessageList :"+e.getMessage(),e);
			}
		}
		return flag;
	}
	
}
